import XEUtils from "@/utils"

/**
 * 合并数组并逗号分割
 *
 * @param array   -需要合并的数组
 * @param object  -提取数组中某个值
 * @param value   -连接的符号(不填默认)
 */
const arrayMerger = function (array: any, object?: any, value?: any) {
    let mergerData = "";
    if (value === null || value === undefined) {
        value = ","
    }
    XEUtils.arrayEach(array, (v: any, i) => {
        if (i === 0) {
            if (object === null || object === undefined) {
                mergerData += v;
            } else {
                mergerData += v[object];
            }
        } else {
            if (object === null || object === undefined) {
                mergerData += value + v;
            } else {
                mergerData += value + v[object];
            }
        }
    })
    return mergerData;
}

/**
 * 判断json数组是否存在对应的值，如不存在，则添加对应的值
 * @param array - 需要判断的json数组
 * @param key - 需要判断的json数组的json主键
 * @param id - 需要添加的id值
 * @param value - 需要添加的显示值
 * @param json - 添加至json数组的json模组
 * @returns {any}
 */
let noHasJsonArrayKeyValue = function (array: any, key = "id", id: any, value: any, json: any) {
    if (XEUtils.isEmpty(json)) json = {id: "", name: ""}

    let tempArray = JSON.parse(JSON.stringify(array));
    if (XEUtils.findIndexOf(tempArray, item => item[key] === id) === -1) {
        let tempJson = {} as any
        XEUtils.objectEach(json, (jsonValue, jsonKey) => {
            tempJson[jsonKey] = value
            if (key === jsonKey) tempJson[jsonKey] = id
        })
        tempArray.push(tempJson)
    }
    return tempArray
}

/**
 * 计算两个时间的时间差，返回X天X小时XX分钟XX秒
 * @param createdTime - 开始时间
 * @param endTime - 结束时间
 * @return {string}
 * */
let differenceTime = function (createdTime: string, endTime: string) {
    if (!createdTime || !endTime) return ""
    let differenceTime = new Date(endTime).getTime() - new Date(createdTime).getTime()
    if (differenceTime < 0) return ""

    let days = Math.floor(differenceTime / (24 * 3600 * 1000))
    let leave1 = differenceTime % (24 * 3600 * 1000)
    let hours = Math.floor(leave1 / (3600 * 1000))
    let leave2 = leave1 % (3600 * 1000)
    let minutes = Math.floor(leave2 / (60 * 1000))
    let leave3 = leave2 % (60 * 1000)
    let seconds = Math.round(leave3 / 1000)
    let returnString = ""
    if (days !== 0) {
        returnString = days + "天" + hours + "小时" + minutes + "分钟" + seconds + "秒"
    } else {
        if (hours !== 0) {
            returnString = hours + "小时" + minutes + "分钟" + seconds + "秒"
        } else {
            if (minutes !== 0) {
                returnString = minutes + "分钟" + seconds + "秒"
            } else {
                if (seconds !== 0) {
                    returnString = seconds + "秒"
                }
            }
        }
    }

    return returnString;
}

/**
 * 数组合并（将主数组中没有的值从从数组中拿取，根据唯一键值判断）
 * @param arrMain       - 主数组
 * @param arrSecond     - 从数组
 * @param key           - 唯一键值
 */
const arrayDeDuplication = (arrMain: any[], arrSecond: any[], key: string): any[] => {
    let returnArray = []
    const arrayMain = JSON.parse(JSON.stringify(arrMain))
    const arraySecond = JSON.parse(JSON.stringify(arrSecond))

    returnArray = arrayMain
    XEUtils.arrayEach(arraySecond, (itemSecond) => {
        const hasValue = XEUtils.findIndexOf(arrayMain, item => jsonJudgeNotDefined(item, `item.${key}`) === jsonJudgeNotDefined(itemSecond, `itemSecond.${key}`)) !== -1
        if (!hasValue) returnArray.push(itemSecond)
    })

    return returnArray
}
/**
 * 数组分组
 * 使用例：const newData = common.arrayGroup(data,(item:any) => item.a)
 * @param arr 数组
 * @param fn  函数 需要的值
 */
const arrayGroup = (arr: any, fn: any) => {
    const obj = {} as any
    arr.forEach((item: any) => {
        const key = JSON.stringify(fn(item));
        obj[key] = obj[key] || [];
        obj[key].push(item)
    });
    return Object.keys(obj).map(k => {
        return obj[k];
    })
}
/**
 * 数组对象排序
 *
 * @param array -排序的数组对象
 * @param key -需要排序的对象key
 * @param string -值为字符串为true，数字为false
 */
const sortArray = (array: any, key: string, string: boolean) => {
    return array.sort((a: any, b: any) => {
        for (let i in a[key]) {
            let index = Number(i)
            if (a[key].charCodeAt(index) == b[key].charCodeAt(index)) {
                return a[key].charCodeAt(index + 1) - b[key].charCodeAt(index + 1)
            }
        }
        if (string) {
            return a[key].charCodeAt(0) - b[key].charCodeAt(0)
        } else {
            return a[key] - b[key]
        }
    })
}

/**
 * 产生任意长度随机字母数字组合
 * @param randomFlag    - 是否任意长度
 * @param min           - 任意长度最小位[固定位数]
 * @param max           - 任意长度最大位
 * @param all           - 字母数字特殊字符
 */
const randomWord = (randomFlag: any, min: any, max?: any, all?: boolean) => {
    let str = "",
        range = min,
        arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'],
        Array = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
    // 随机产生
    if (randomFlag) {
        range = Math.round(Math.random() * (max - min)) + min;
    }
    if (all) {
        for (let i = 0; i < range; i++) {
            let pos = Math.round(Math.random() * (Array.length - 1));
            str += Array[pos];
        }
    }
    for (let i = 0; i < range; i++) {
        let pos = Math.round(Math.random() * (arr.length - 1));
        str += arr[pos];
    }
    return str;
}


/**
 * 对cronExpression数据进行解析
 * @param cronExpression
 */
export const cronExpressionDataAnalysis = (cronExpression: string) => {
    let returnData = {} as any
    if (!jsonJudgeNotDefined(cronExpression, "cronExpression")) return null;
    let cronExpressionArray = cronExpression.split(' ')
    returnData.month = cronExpressionArray[2]
    returnData.week = cronExpressionArray[4]
    returnData.hour = cronExpressionArray[1]
    returnData.minute = cronExpressionArray[0]
    returnData.time = cronExpressionArray[1] + " " + cronExpressionArray[0]
    if (cronExpressionArray[2] !== "*") {
        returnData.type = 'month'
        returnData.typeDisplay = '月'
    } else if (cronExpressionArray[4] !== "*") {
        returnData.type = 'week'
        returnData.typeDisplay = '周'
    } else {
        returnData.type = 'day'
        returnData.typeDisplay = '天'
    }

    return returnData
}

/**
 * 判断json是否未定义
 * @param jsonData  - 需要判断的整个json数据
 * @param jsonStr   - 需要判断的json路径
 */
export const jsonJudgeNotDefined = (jsonData: any, jsonStr: string): any => {
    let jsonArray = jsonStr.split(".");
    let forData = jsonData;
    let returnValue = '';
    let returnArray = [];
    let arrayFlag = false;
    let arrayIndex = 0;
    for (let i = 0; i < jsonArray.length; i++) {
        if (forData === null || forData === undefined) break;
        if (i !== jsonArray.length - 1) {
            if (jsonArray[i + 1].split("<>").length === 1) {
                forData = forData[jsonArray[i + 1]]
            } else {
                arrayFlag = true
                arrayIndex = i + 1
                forData = forData[jsonArray[i + 1].split("<>")[0]]
                jsonArray.splice(0, arrayIndex)
                break;
            }
        } else {
            returnValue = forData
        }
    }
    if (arrayFlag) {
        if (forData === null || forData === undefined) return ""
        if (forData.length !== 0) {
            for (let i = 0; i < forData.length; i++) returnArray.push(jsonJudgeNotDefined(forData[i], jsonArray.join(".")))
            let flag = false
            for (let i = 0; i < returnArray.length; i++) if (returnArray[i] !== null && returnArray[i] !== "") flag = true
            if (flag) {
                return returnArray
            }
            return ""
        }
    }
    return returnValue
}

export default {
    cronExpressionDataAnalysis,
    randomWord,
    arrayMerger,
    noHasJsonArrayKeyValue,
    differenceTime,
    arrayDeDuplication,
    arrayGroup,
    sortArray
}